package com.gitee.deeround.javaprotect.agent;

import com.gitee.deeround.javaprotect.agent.util.CommonUtils;
import com.gitee.deeround.javaprotect.agent.util.HexUtil;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class E implements IE {

    private static final String ALGORITHM = "AES";
    private static final String AES_ECB_PADDING = "AES/ECB/PKCS5Padding";

    private P p;

    public E(P p) {
        this.p = p;

        String k = this.dk(p.s());

        try {
            SecretKey secretKey = new SecretKeySpec(k.getBytes(StandardCharsets.UTF_8), ALGORITHM);
            cipher = Cipher.getInstance(AES_ECB_PADDING);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        } catch (Exception e) {
            throw new RuntimeException("Decryption tool initialization error");
        }
    }

    private Cipher cipher;

    @Override
    public String dk(String k) {
        try {
            k = p.s();
            byte[] bytes = d(HexUtil.decodeHex(k), "D25C85E7EB9D077E".getBytes(StandardCharsets.UTF_8));
            k = new String(bytes, StandardCharsets.UTF_8);
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i < k.toCharArray().length; i = i + 2) {
                sb.append(k.charAt(i));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("Decryption agent key error");
        }
    }

    @Override
    public String en(String n) {
        try {
            return CommonUtils.getMD5(n);
        } catch (Exception e) {
            throw new RuntimeException("Encryption failed");
        }
    }

    @Override
    public byte[] d(byte[] d) {
        try {
            return cipher.doFinal(d);
        } catch (Exception e) {
            throw new RuntimeException("Decryption failed");
        }
    }

    private byte[] d(byte[] d, byte[] k) {
        try {
            SecretKey secretKey = new SecretKeySpec(k, ALGORITHM);
            Cipher cipher1 = Cipher.getInstance(AES_ECB_PADDING);
            cipher1.init(Cipher.DECRYPT_MODE, secretKey);
            return cipher1.doFinal(d);
        } catch (Exception e) {
            throw new RuntimeException("Decryption failed");
        }
    }

    public static void main(String[] args) {
        E ee = new E(new P("bf2ca1565ea940f466035de853e575c32a5aac37ac985b5b0c91af434bfd62021a29a2ab38091046ff3f43c0740f53005939f8d564cfaf431f1cd23227c2a4753b40005f459d7b74333aa978306132ae"));
        ee.d("111".getBytes(StandardCharsets.UTF_8));
    }
}
